package download;

import util.FileUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Description  管理多任务
 * @Author 冷彭磊
 * @Data 2025/2/26 9:09
 */

public class DownloadManager2 {
    private final List<DownloadTask2> tasks = new ArrayList<>();
    private static final int POOL_SIZE = 10;
    private final ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);

    public void addDownloadTask(String url, String savePath, int threads ,String md5) {
        //判断此任务是否支持断点续传
        final boolean breakpointContinuation = new FileUtils().isBreakpointContinuation(url);
        //判断文件是否已经下载
        if (new FileUtils().isFileExist(savePath,md5)){
            System.out.println(savePath + "文件已经存在");
        }else{
            DownloadListener listener = new ConsoleDownloadListener();
            tasks.add(new DownloadTask2(url, savePath, threads,listener,md5,breakpointContinuation));
        }
    }

    public void startAll() {
        for (DownloadTask2 task : tasks) {
            try {
                task.download(executor);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
}
}